package com.ruicar.afs.cloud.afscase.channel.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.channel.condition.AffiliationCondition;
import com.ruicar.afs.cloud.afscase.channel.condition.AffiliationStatusCondition;
import com.ruicar.afs.cloud.afscase.channel.condition.BaseInfoTypeDTO;
import com.ruicar.afs.cloud.afscase.channel.condition.ChannelAffiliatedCondition;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAffiliatedUnits;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAffiliatedUnitsRel;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAffiliatedUnitsRelService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAffiliatedUnitsService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.utils.Common;
import com.ruicar.afs.cloud.afscase.channel.utils.RoleTypeDic;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.AffiiationEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.AffiliatedWayEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * @author panhj
 * @date 2020/6/2
 * ChannelAffiliatedUnitsTempController class function description.
 */

@RestController
@AllArgsConstructor
@Api("渠道挂靠接口")
@RequestMapping("/caseChannel")
public class ChannelAffiliatedUnitsController {
    private ChannelAffiliatedUnitsService channelAffiliatedUnitsService;
    private ChannelAffiliatedUnitsRelService channelAffiliatedUnitsRelService;
    private ChannelBaseInfoService channelBaseInfoService;

    @PostMapping(value = "/upDateCaseStatusByIds/{ids}")
    @ApiOperation(value = "根据id停用挂靠公司")
    public IResponse upDateCaseStatusByIds(@PathVariable String ids) {
        //截取字符串
        String[] idArray = ids.split(",");
        for (int j = 0; j < idArray.length; j++) {
            Long id = Long.valueOf(idArray[j].toString());
            ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(id);
            if (channel != null) {
                channel.setStatus(Common.STATUS_STOP);
                channel.setUpdateTime(new Date(System.currentTimeMillis()));
                channel.setUpdateBy(SecurityUtils.getUsername());
                channelAffiliatedUnitsService.updateById(channel);
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }

    @PostMapping(value = "/upDateCaseStatusByIdsForApply")
    @ApiOperation(value = "根据id停用挂靠公司")
    public IResponse upDateCaseStatusByIdsForApply(@RequestBody String ids) {
        //截取字符串
        String[] idArray = ids.split(",");
        for (int j = 0; j < idArray.length; j++) {
            Long id = Long.valueOf(idArray[j].toString());
            ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(id);
            if (channel != null) {
                channel.setStatus(Common.STATUS_STOP);
                channel.setUpdateTime(new Date(System.currentTimeMillis()));
                channel.setUpdateBy(SecurityUtils.getUsername());
                channelAffiliatedUnitsService.updateById(channel);
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }

    @PostMapping(value = "/saveThirdOrNetCar")
    @ApiOperation(value = "同步第三方网约车挂靠申请")
    public IResponse saveThirdOrNetCar(@Valid @RequestBody ChannelAffiliatedCondition channelAffiliatedCondition) {
        ChannelAffiliatedUnits channelAffiliatedUnits = channelAffiliatedCondition.getChannelAffiliatedUnits();
        List<ChannelAffiliatedUnitsRel> channelAffiliatedUnitsRelList = channelAffiliatedCondition.getChannelAffiliatedUnitsRelList();
        ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(channelAffiliatedUnits.getId());
        if (channel == null) {
            channelAffiliatedUnitsService.save(channelAffiliatedUnits);
        } else {
            channelAffiliatedUnitsService.updateById(channelAffiliatedUnits);
        }
        for (int i = 0; i < channelAffiliatedUnitsRelList.size(); i++) {
            ChannelAffiliatedUnitsRel channelAffiliatedUnitsRel = channelAffiliatedUnitsRelService.getById(channelAffiliatedUnitsRelList.get(i).getId());
            if (channelAffiliatedUnitsRel == null) {
                channelAffiliatedUnitsRelService.save(channelAffiliatedUnitsRelList.get(i));
            } else {
                channelAffiliatedUnitsRelService.updateById(channelAffiliatedUnitsRelList.get(i));
            }
        }
        return IResponse.success("操作成功");
    }


    @RequestMapping(value = "/getAffiliationInfo", method = RequestMethod.GET)
    @ApiOperation(value = "根据条件获取挂靠公司列表")
    public IResponse getAffiliationInfo(@RequestParam String channelId, String affiliatedType, String affUnitsName) {
        if (channelId == null || channelId == "") {
            return IResponse.fail("渠道id不能为空");
        }
        if (affiliatedType == null || affiliatedType == "") {
            return IResponse.fail("挂靠类型不能为空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        List<ChannelAffiliatedUnits> listInfo = channelAffiliatedUnitsService.getAffiliationInfo(Long.parseLong(channelId), affiliatedType, affUnitsName);
        return IResponse.success(listInfo);
    }

    @RequestMapping(value = "/getCooperPlatList", method = RequestMethod.GET)
    @ApiOperation(value = "获取网约车合作平台")
    public IResponse getCooperPlatList(@RequestParam String socUniCrtCode) {
        if (socUniCrtCode == null || socUniCrtCode == "") {
            return IResponse.fail("社会统一信用代码不能为空");
        }
        ChannelAffiliatedUnits channelAffiliatedUnits = channelAffiliatedUnitsService.getOne(Wrappers.<ChannelAffiliatedUnits>query().lambda()
                .eq(ChannelAffiliatedUnits::getBusiType, AffiliatedWayEnum.NETWORK_CAR_AFFILIATED.getCode())
                .eq(ChannelAffiliatedUnits::getSocUniCrtCode, socUniCrtCode)
                .eq(ChannelAffiliatedUnits::getStatus, AffiiationEnum.START.getCode()));
        List coorlist = new ArrayList();
        Map map = new HashMap();
        if (channelAffiliatedUnits != null) {
            String id = channelAffiliatedUnits.getId().toString();
            String province = channelAffiliatedUnits.getRegisteredProvince();
            String city = channelAffiliatedUnits.getRegisteredProvince();
            map.put("id", id);
            map.put("province", province);
            map.put("city", city);
            String coor = channelAffiliatedUnits.getCooperPlat();
            String[] idArray = coor.split(",");
            for (int j = 0; j < idArray.length; j++) {
                coorlist.add(idArray[j]);
            }
            map.put("cooperPlat", coorlist);
        }
        return IResponse.success(map);
    }

    @PostMapping(value = "/upStatusByChannelIds")
    @ApiOperation(value = "黑名单根据id停用挂靠公司")
    public IResponse upStatusByChannelIds(@RequestBody List<Long> ids) {
        //截取字符串
        if (ids.size() > 0) {
            for (int j = 0; j < ids.size(); j++) {
                ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(ids.get(j));
                if (channel != null) {
                    channel.setStatus(Common.STATUS_STOP);
                    channel.setUpdateTime(new Date(System.currentTimeMillis()));
                    channel.setUpdateBy(SecurityUtils.getUsername());
                    boolean result = channelAffiliatedUnitsService.updateById(channel);
                    if (!result) {
                        return IResponse.fail("状态更新失败！");
                    }
                }
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }

    @PostMapping(value = "/upDateCaseStatusByIdsPass")
    @ApiOperation(value = "黑名单根据id停用挂靠公司")
    public IResponse upDateCaseStatusByIdsPass(@RequestBody List<Long> ids) {
        //截取字符串
        if (ids.size() > 0) {
            for (int j = 0; j < ids.size(); j++) {
                ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(ids.get(j));
                if (channel != null) {
                    channel.setStatus(Common.STATUS_ENABLE);
                    channel.setUpdateTime(new Date(System.currentTimeMillis()));
                    channel.setUpdateBy(SecurityUtils.getUsername());
                    boolean result = channelAffiliatedUnitsService.updateById(channel);
                    if (!result) {
                        return IResponse.fail("状态更新失败！");
                    }
                }
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }

    @PostMapping(value = "/getBaseInfo")
    @ApiOperation(value = "根据条件获取挂靠公司列表")
    public IResponse getBaseInfo(@RequestBody AffiliationStatusCondition affiliationStatusCondition) {
        List<ChannelBaseInfo> list = channelBaseInfoService.getBaseInfo(affiliationStatusCondition);
        return IResponse.success(list);
    }

    @PostMapping(value = "/getBaseInfoPage")
    @ApiOperation(value = "根据条件获取挂靠公司列表")
    public IResponse getBaseInfoPage(@RequestBody AffiliationStatusCondition affiliationStatusCondition) {
        Page page = new Page(affiliationStatusCondition.getPageNumber(), affiliationStatusCondition.getPageSize());
        IPage<List<ChannelBaseInfo>> list = channelBaseInfoService.getBaseInfoPage(page, affiliationStatusCondition);
        return IResponse.success(list);
    }

    @PostMapping(value = "/getBaseInfoByType")
    @ApiOperation(value = "根据合作商类型查询全部")
    public IResponse getBaseInfoByType(@RequestBody BaseInfoTypeDTO dto) {
        List<ChannelBaseInfo> list = channelBaseInfoService.getBaseInfoByType(dto);
        return IResponse.success(list);
    }
    @RequestMapping(value = "/affiliatedCount")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("进件申请挂靠数量计算")
    public IResponse affiliatedCount(@RequestParam String id) {
        ChannelAffiliatedUnits channelAffiliatedUnits=channelAffiliatedUnitsService.getById(id);
        if(channelAffiliatedUnits!=null){
            if(channelAffiliatedUnits.getMonthlySurplusNum()==0||channelAffiliatedUnits.getTotalSurplusNum()==0){
                return IResponse.fail("该挂靠公司申请数量已用尽");
            }
            channelAffiliatedUnits.setMonthlySurplusNum(channelAffiliatedUnits.getMonthlySurplusNum()-1);
            channelAffiliatedUnits.setTotalSurplusNum(channelAffiliatedUnits.getTotalSurplusNum()-1);
            channelAffiliatedUnitsService.updateById(channelAffiliatedUnits);
            return IResponse.success("申请成功");
        }else{
            return IResponse.fail("未获取到挂靠信息");

        }
    }

    @PostMapping(value = "/getBaseInfoByRole")
    @ApiOperation(value = "根据角色属性查询渠道信息")
    public IResponse getBaseInfoByRole(@RequestBody BaseInfoTypeDTO dto) {
        List<ChannelBaseInfo> list = new ArrayList<>();
        // 先判断是不是直营和非直营都有
        if(dto.getBusinessType()!=null&&dto.getBusinessType()!=""&&dto.getOwnBusinessType()!=null&&dto.getOwnBusinessType()!=""){
            // 进入这里就说明  既可以做直营也可以做非直营
            if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                // 进入这里说明直营非直营  新车二手车都能做
                list =channelBaseInfoService.getBaseInfoByStatus(dto);
                return IResponse.success(list);
            }
            if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&!RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                //  说明  非直营的查看新车二手车  直营的只能做单一的类型
                list =channelBaseInfoService.getBaseInfoByStatusOtherAll(dto);
                return IResponse.success(list);
            }
            if(RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())&&!RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())){
                // 说明 直营新车二手车都可以做   非直营只能做单一的类型
                list =channelBaseInfoService.getBaseInfoByStatusOwnAll(dto);
                return IResponse.success(list);
            }
            if(!RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&!RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                // 进入这里说明 非直营是单一类型  直营是单一类型
                list =channelBaseInfoService.getBaseInfoByStatusOtherOnlyOwnOnly(dto);
                return IResponse.success(list);
            }

        }
        if((dto.getBusinessType()==null||dto.getBusinessType()=="")&&(dto.getOwnBusinessType()!=null&&dto.getOwnBusinessType()!="")){
            // 说明只有 直营   没有非直营权限
            if(RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                // s 说明直营的可以查看新车和二手车
                list =channelBaseInfoService.getBaseInfoByStatusOnlyOwnAll(dto);
                return IResponse.success(list);
            }else {
                // 说明直营的只有单一权限
                list =channelBaseInfoService.getBaseInfoByStatusOnlyOwnType(dto);
                return IResponse.success(list);
            }

        }
        if((dto.getOwnBusinessType()==null||dto.getOwnBusinessType()=="")&&(dto.getBusinessType()!=null&&dto.getBusinessType()!="")){
            // 说明只有非直营  没有 直营权限
            if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())){
                // 说明 非直营的新车二手车都能看
                list =channelBaseInfoService.getBaseInfoByStatusOnlyOtherAll(dto);
                return IResponse.success(list);
            }else {
                // 说明非直营的  只有单一属性
                list =channelBaseInfoService.getBaseInfoByStatusOnlyOtherType(dto);
                return IResponse.success(list);
            }
        }
        if(dto.getBusinessType()==null&&dto.getOwnBusinessType()==null&&dto.getChannelId()!=null){
            ChannelBaseInfo bb =channelBaseInfoService.getById(dto.getChannelId());
            list.add(bb);
        }

        return IResponse.success(list);
    }

    @PostMapping(value = "/getAffiliatedById")
    @ApiOperation(value = "根据id获取挂靠公司信息")
    public ChannelAffiliatedUnits getAffiliatedById(@RequestBody AffiliationCondition condition) {
        ChannelAffiliatedUnits channel = channelAffiliatedUnitsService.getById(condition.getId());
        return  channel;
    }
}
